package com.hiep.connect.client.view;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment.HorizontalAlignmentConstant;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.MenuItem;
import com.google.gwt.user.client.ui.MultiWordSuggestOracle;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.StackPanel;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DatePicker;
import com.hiep.connect.client.MyCommand;
import com.hiep.connect.client.UiUtils;
import com.hiep.connect.client.presenter.HomeViewPresenter.HomeDisplay;
import com.hiep.connect.shared.MyUser;
import com.hiep.connect.shared.PostingThread;

public class HomeView extends Composite implements HomeDisplay {
	private MyUser user;

	private Label status;

	private MenuItem logoutItem;

	private Tree tree;

	private SuggestBox searchBox;

	private TextBox postField;

	private ScrollPanel contentScrollPanel;
	private VerticalPanel contentPanel;

	private MultiWordSuggestOracle oracle;
	private Button postButton;

	private List<MenuItem> friendItems;

	public HomeView(MyUser user, MultiWordSuggestOracle oracle) {
		this.user = user;
		this.oracle = oracle;
		initGui();
	}

	private void postMyStatus() {
		// TODO Auto-generated method stub
		String status = postField.getText().trim();
		contentPanel.add(new Label(status));

	}

	private HorizontalPanel getPostPanel() {
		postField = new TextBox();
		postField.setWidth("300px");
		postField.addKeyUpHandler(new KeyUpHandler() {

			@Override
			public void onKeyUp(KeyUpEvent event) {
				// TODO Auto-generated method stub
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					postMyStatus();

				}

			}
		});

		postButton = new Button("Share Status");
		postButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				// TODO Auto-generated method stub
				postMyStatus();
			}
		});
		HorizontalPanel panel = new HorizontalPanel();
		panel.setStylePrimaryName("Hiep-Popup");
		panel.setSpacing(5);
		panel.add(postField);
		panel.add(postButton);
		panel.setWidth("50%");
		return panel;
	}

	private void initGui() {
		status = new Label("Status");
		ScrollPanel contentScrollPanel = getContentPanel();
		DockPanel mainPanel = new DockPanel();

		mainPanel.add(getFirstNorthPanel(), DockPanel.NORTH);
		mainPanel.add(getSecondNorthPanel(), DockPanel.NORTH);
		mainPanel.add(getNavigationPanel(user), DockPanel.WEST);
		mainPanel.add(contentScrollPanel, DockPanel.CENTER);
		mainPanel.add(UiUtils.getSouthPanel(), DockPanel.SOUTH);

		ScrollPanel mainScrollPanel = new ScrollPanel(mainPanel);

		FlexTable contentTable = new FlexTable();
		contentTable.setWidth("100%");
		contentTable.getCellFormatter().addStyleName(0, 0,
				"contacts-ListContainer");
		contentTable.getCellFormatter().setWidth(0, 0, "100%");
		contentTable.getFlexCellFormatter().setVerticalAlignment(0, 0,
				DockPanel.ALIGN_TOP);
		contentTable.setWidget(1, 1, mainScrollPanel);

		DecoratorPanel contentTableDecorator = new DecoratorPanel();
		initWidget(contentTableDecorator);
		contentTableDecorator.setWidth("100%");
		contentTableDecorator.setWidth("18em");
		contentTableDecorator.add(contentTable);

	}

	private HorizontalPanel getFirstNorthPanel() {
		HorizontalPanel northPanel = new HorizontalPanel();
		northPanel.setSpacing(10);
		northPanel.add(UiUtils.getLogoPanel());

		VerticalPanel northEastPanel = new VerticalPanel();
		northEastPanel.add(UiUtils.createFileUpload());
		// northEastPanel.add(getMenuBar());

		northPanel.add(northEastPanel);
		northPanel.setStyleName("hiep-North");
		northPanel.setWidth("100%");

		northPanel.add(intSearchBox());
		return northPanel;
	}

	private HorizontalPanel getSecondNorthPanel() {
		Hyperlink userHomeLink = new Hyperlink(user.getEmail() + " home",
				"home");

		HorizontalPanel northPanel = new HorizontalPanel();

		northPanel.setSpacing(10);
		northPanel.add(userHomeLink);
		northPanel.add(getPostPanel());

		MenuBar menuBar = getMenuBar();
		northPanel.add(menuBar);
		northPanel.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT);
		return northPanel;
	}

	private ScrollPanel getContentPanel() {
		contentPanel = new VerticalPanel();
		contentPanel.setSpacing(5);
		contentPanel.setSize("700px", "350px");

		contentPanel.add(status);
		List<PostingThread> postingThreads = user.getPostingThreads();
		if (postingThreads != null) {
			for (PostingThread thread : postingThreads) {
				ThreadPanel theadPanel = new ThreadPanel(user.getEmail(),
						thread);
				contentPanel.add(theadPanel.asWidget());
			}

		}

		contentScrollPanel = new ScrollPanel(contentPanel);
		contentScrollPanel.setSize("720px", "370px");
		return contentScrollPanel;
	}

	private MenuBar getMenuBar() {

		// Create a menu bar
		MenuBar menu = new MenuBar();
		menu.setAutoOpen(true);
		menu.setAnimationEnabled(true);

		// Create a command that will execute on menu item selection
		Command menuCommand = new Command() {
			private int curPhrase = 0;
			private final String[] phrases = { "phase 1", "phase 2" };

			public void execute() {
				Window.alert(phrases[curPhrase]);
				curPhrase = (curPhrase + 1) % phrases.length;
			}
		};

		// Create the help menu
		MenuBar gwtMenu = new MenuBar(true);

		// Create accept friend menu item
		List<MyUser> pendingFriends = user.getPendingFriends();
		if (pendingFriends != null && pendingFriends.size() > 0) {
			MenuBar acceptFrientMenu = new MenuBar(true);

			menu.addItem(new MenuItem("Accept Friends", true, acceptFrientMenu));
			friendItems = new ArrayList<MenuItem>();
			for (MyUser u : pendingFriends) {
				MenuItem item = new MenuItem((SafeHtmlUtils.fromSafeConstant(u
						.getEmail())));
				friendItems.add(item);
				acceptFrientMenu.addItem(item);

			}
			menu.addSeparator();
		}

		menu.addItem(new MenuItem("Help", true, gwtMenu));
		String[] gwtOptions = { "Help Topic 1", "Help Topic 2" };
		for (int i = 0; i < gwtOptions.length; i++) {
			gwtMenu.addItem(gwtOptions[i], menuCommand);
		}

		// Create the logout menu
		menu.addSeparator();
		logoutItem = new MenuItem("Logout", menuCommand);
		logoutItem.setTitle("Log out of this account");
		menu.addItem(logoutItem);

		// Return the menu
		menu.ensureDebugId("cwMenuBar");
		return menu;
	}

	@Override
	public Widget asWidget() {
		// TODO Auto-generated method stub
		return this;
	}

	@Override
	public void setModel(MyUser user) {
		// TODO Auto-generated method stub
		this.user = user;
	}

	private StackPanel getNavigationPanel(MyUser user) {
		StackPanel navigationPanel = new StackPanel();
		String text1 = "Lorem ipsum dolor sit amet...";
		String text2 = "Sed egestas, arcu nec accumsan...";
		String text3 = "Proin tristique, elit at blandit...";

		Label label;
		label = new Label(text1);

		navigationPanel.add(getFriendTree(user), "Friend", false);

		label = new Label(text2);

		VerticalPanel calendarPanel = getCalendarPanel();
		navigationPanel.add(calendarPanel, "Event", false);
		label = new Label(text3);

		Hyperlink loginInfoLink = new Hyperlink("User Info", "editProfile");
		Hyperlink privacyLink = new Hyperlink("Privacy Setting", "login");
		VerticalPanel linkPanel = new VerticalPanel();
		linkPanel.add(loginInfoLink);
		linkPanel.add(privacyLink);

		navigationPanel.add(linkPanel, "Account Setting", false);
		navigationPanel.setSize("200px", "420px");
		navigationPanel.addStyleName("demo-panel");

		return navigationPanel;
	}

	private VerticalPanel getCalendarPanel() {
		final DatePicker datePicker = new DatePicker();
		datePicker.setWidth("100%");
		datePicker.addValueChangeHandler(new ValueChangeHandler<Date>() {

			@Override
			public void onValueChange(ValueChangeEvent<Date> event) {
				status.setText("Date selected " + event.getValue());
			}
		});

		VerticalPanel calendarPanel = new VerticalPanel();
		calendarPanel.setWidth("100%");
		calendarPanel.add(datePicker);
		Button todayButton = new Button("Today");
		todayButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				// TODO Auto-generated method stub
				datePicker.setValue(new Date(), true);
			}
		});
		calendarPanel.add(todayButton);

		return calendarPanel;
	}

	private VerticalPanel intSearchBox() {
		// Create the suggest box
		searchBox = new SuggestBox(oracle);
		searchBox.addValueChangeHandler(new ValueChangeHandler<String>() {

			@Override
			public void onValueChange(ValueChangeEvent<String> event) {
				// TODO Auto-generated method stub
				status.setText("Searching " + event.getValue());
			}
		});

		searchBox.ensureDebugId("cwSuggestBox");
		VerticalPanel suggestPanel = new VerticalPanel();
		suggestPanel.add(new HTML("Search"));
		suggestPanel.add(searchBox);

		// Return the panel
		return suggestPanel;
	}

	public Tree getFriendTree(MyUser user) {

		// List<FriendGroup> friendGroups = user.getFriendGroups();
		List<MyUser> friends = user.getFriends();
		tree = new Tree();

		// if (friendGroups != null && friendGroups.size() > 0) {
		// for (FriendGroup group : friendGroups) {
		// TreeItem groupItem = new TreeItem(group.getName());
		//
		// List<MyUser> members = group.getMembers();
		// for (MyUser u : members) {
		// // Add friends to group.
		// Image image = new Image("images/person.png");
		// HorizontalPanel itemPanel = new HorizontalPanel();
		// itemPanel.add(image);
		// itemPanel.add(new Label(u.getEmail()));
		// groupItem.addItem(itemPanel);
		// // groupItem.addItem(u.getEmail());
		// }
		// // Add group to tree.
		// tree.addItem(groupItem);
		// }
		// } else
		if (friends != null && friends.size() > 0) {
			// TODO process friends
			for (MyUser friend : friends) {
				TreeItem friendItem = new TreeItem(friend.getEmail());

				Image image = new Image("images/person.png");
				HorizontalPanel itemPanel = new HorizontalPanel();
				itemPanel.add(image);
				itemPanel.add(new Label(friend.getEmail()));
				tree.addItem(itemPanel);

				// tree.addItem(friendItem);
			}
		}

		tree.addSelectionHandler(new SelectionHandler<TreeItem>() {

			@Override
			public void onSelection(SelectionEvent<TreeItem> event) {
				// TODO Auto-generated method stub
				TreeItem selectedItem = event.getSelectedItem();
				status.setText(selectedItem.getText() + " selected");
			}
		});

		return tree;
	}

	@Override
	public void setLogoutCommand(Command logoutCommand) {
		// TODO Auto-generated method stub
		logoutItem.setCommand(logoutCommand);
	}

	@Override
	public Tree getTree() {
		// TODO Auto-generated method stub
		return tree;
	}

	@Override
	public Label getStatus() {
		// TODO Auto-generated method stub
		return status;
	}

	@Override
	public ScrollPanel getContentScrollPanel() {
		// TODO Auto-generated method stub
		return contentScrollPanel;
	}

	@Override
	public void setSearchHandler(KeyUpHandler handler) {
		// TODO Auto-generated method stub
		searchBox.addKeyUpHandler(handler);
	}

	@Override
	public SuggestBox getSuggestBox() {
		// TODO Auto-generated method stub
		return searchBox;
	}

	@Override
	public void setAcceptFriendCommand(Command acceptCommand) {
		// TODO Auto-generated method stub
		if (friendItems != null) {
			for (MenuItem i : friendItems) {
				i.setCommand(acceptCommand);
			}
		}

	}

}
